package com.example.module_filemanage.MVVM.View;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.speech.RecognizerIntent;
import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.view.GravityCompat;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.MenuItem;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.bumptech.glide.Glide;
import com.example.module_base.Base.BaseActivity;
import com.example.module_base.Controll.MyToolBar;
import com.example.module_base.Controll.SwitchButton;
import com.example.module_base.Util.RecyclerItemClickListener;
import com.example.module_filemanage.Adapter.LeftMenu_Adapter;
import com.example.module_filemanage.Control.SearchView;
import com.example.module_filemanage.Interface.IFileInfoOnclickListener;
import com.example.module_filemanage.Interface.ICallBack;
import com.example.module_filemanage.MVVM.Module.Business.TranModule;
import com.example.module_filemanage.MVVM.Module.Entil.Item_FileInfo_module;
import com.example.module_filemanage.MVVM.Module.QiNiu.FileManager2;
import com.example.module_filemanage.MVVM.View.Dialog.MDialog;
import com.example.module_filemanage.MVVM.View.Fragment.FM_File_Info_fragment;
import com.example.module_filemanage.MVVM.View.Fragment.FM_ShowPicture_fragment;
import com.example.module_filemanage.MVVM.ViewModule.FMMain_VM;
import com.example.module_filemanage.Public.BodyColor;
import com.example.module_filemanage.Public.Data;
import com.example.module_filemanage.R;
import com.example.module_filemanage.Utils.FilePath;
import com.example.module_filemanage.Utils.UltimateBar;
import com.example.module_filemanage.databinding.FmActivityMainBinding;
import com.miguelcatalan.materialsearchview.MaterialSearchView;

import java.util.ArrayList;


@Route(path="/filemanage/main")
public class FMMainActivity extends BaseActivity<FmActivityMainBinding> implements View.OnClickListener{
    public FmActivityMainBinding binding;
    FMMain_VM _fmMain_vm;
    Toolbar toolbar;
    private static final int REQUESTCODE = 866;
    private final String fragmentflag="spacefragment";
    @Override
    public int setLayout() {
        return R.layout.fm_activity_main;
    }

    @SuppressLint("ResourceType")
    @Override
    public void init(final FmActivityMainBinding binding) {
        this.binding=binding;
         toolbar=new MyToolBar(this)
                .init(binding.fmmain.toolbarMain)
                .addTitle("七牛云存储")
                .addLogo()
                .setOverflowIcon()
                .addMenu(R.menu.fm_main_menu, new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        int i = item.getItemId();
                        if (i == R.id.menu_uploadfile) {
                            new AlertDialog.Builder(FMMainActivity.this) // build AlertDialog
                                    .setTitle("选择类型(图片建议压缩)") // title
                                    .setItems(R.array.upload_select, new  DialogInterface.OnClickListener() { //content
                                        @Override
                                        public void onClick(DialogInterface dialog, int which) {
                                            switch (which){
                                                case 0:
                                                    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
                                                    intent.setType("*/*");//设置类型，我这里是任意类型，任意后缀的可以这样写。
                                                    intent.addCategory(Intent.CATEGORY_OPENABLE);
                                                   startActivityForResult(intent,REQUESTCODE);
                                                    break;
                                                case 1:
                                                    Intent intent2 = new Intent(Intent.ACTION_GET_CONTENT);
                                                    intent2.setType("image/*");//选择图片  
                                                    intent2.addCategory(Intent.CATEGORY_OPENABLE);
                                                    startActivityForResult(intent2,REQUESTCODE);
                                                    break;

                                            }

                                        }
                                    }) .show();
                        }else if (i==R.id.menu_refreshfile){
                            onBindData();
                        }
                        return false;
                    }
                })
                .setColor(Color.TRANSPARENT,getResources().getColor(R.color.white))
                .addHome(0, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        binding.drawerLayout.openDrawer(Gravity.START);
                    }
                });
        Data.account="沙杰";
        Data.accounts=new String[]{"沙杰","陈煜","沙俊"};
        Glide.with( this ).load( R.drawable.bk_qiniu_main2 ).asBitmap().into( binding.fmmain.qiniuMain );
        Glide.with( this ).load( R.drawable.bk_menu_head ).asBitmap().into( binding.includeHeard.imageView );
        changeBodyColor();

         UltimateBar.newDrawerBuilder()
                .statusColor(getResources().getColor(R.color.darkslateblue))     // 状态栏颜色
                .statusDepth(0)         // 状态栏颜色深度
                .applyNav(true)         // 是否应用到导航栏
                .navColor(getResources().getColor(R.color.darkslateblue))     // 导航栏颜色
                .navDepth(0)            // 导航栏颜色深度
                .build(this)
                .apply();
        int permission = ActivityCompat.checkSelfPermission(FMMainActivity.this, Manifest.permission.WRITE_EXTERNAL_STORAGE);

        if (permission != PackageManager.PERMISSION_GRANTED) {
            // We don't have permission so prompt the user
            ActivityCompat.requestPermissions(
                    FMMainActivity.this,
                    PERMISSIONS_STORAGE,
                    REQUEST_EXTERNAL_STORAGE
            );
        }
        initSearch();
        onBindData();
        binding.setOnclicklistener(this);
        //左边菜单recycler
        binding.includeMenu.recSpacemenu.addOnItemTouchListener(new RecyclerItemClickListener(getApplicationContext(), new RecyclerItemClickListener.OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {

                binding.drawerLayout.closeDrawer(Gravity.START);
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        //.setCustomAnimations(null,null,R.anim.out_from_left,R.anim.out_from_right)
                        .add(R.id.drawer_layout, FM_File_Info_fragment.getInstance(Data.getInstance().SPACES.get(position),Data.accounts),fragmentflag)
                        .commit();
                binding.drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
            }

            @Override
            public void onLongClick(View view, int posotion) {

            }
        }));

    }
    //搜索初始化
    private void initSearch(){
        MenuItem item = binding.fmmain.toolbarMain.getMenu().findItem(R.id.menu_searchfile);
        binding.fmmain.searchBar.setMenuItem(item);
        binding.fmmain.searchBar.setVoiceSearch(false);
        binding.fmmain.searchBar.setEllipsize(true);
        binding.fmmain.searchBar.setHint("若无结果可点击搜索智能匹配");
        binding.fmmain.searchBar.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                Toast.makeText(FMMainActivity.this, query, Toast.LENGTH_SHORT).show();
                binding.fmmain.searchBar.closeSearch();
                //界面跳转
                getSupportFragmentManager().beginTransaction()
                        .addToBackStack(null)
                        .setCustomAnimations(R.anim.in_from_left,R.anim.in_from_right,R.anim.out_from_left,R.anim.out_from_right)
                        .add(R.id.drawer_layout, FM_File_Info_fragment.getInstance("匹配结果",Data.accounts),fragmentflag)
                        .commit();
                return false;
            }

            @Override
            public boolean onQueryTextChange(String newText) {

                if (binding.fmmain.searchBar.isclick){
                    //界面跳转
                }
                binding.fmmain.searchBar.isclick=false;
                return false;
            }
        });
        binding.fmmain.searchBar.setOnSearchViewListener(new SearchView.SearchViewListener() {
            @Override
            public void onSearchViewShown() {

            }

            @Override
            public void onSearchViewClosed() {

            }
        });
    }
    //初始化皮肤
    private void initBody(){
        binding.includeMenu.constlayout.setBackgroundColor(getResources().getColor(BodyColor.background));
      //  binding.fmmain.llMain.setBackgroundColor(getResources().getColor(BodyColor.maincolor));
        //_fmMain_vm._leftMenu_adapter.setBackground();
        //设置选中效果
        for (int i=0; i <_fmMain_vm._leftMenu_adapter.getItemCount() ; i++) {
            View v=binding.includeMenu.recSpacemenu.getChildAt(i);
            LeftMenu_Adapter.LeftMenu_ViewHolder  viewHolder=(LeftMenu_Adapter.LeftMenu_ViewHolder)binding.includeMenu.recSpacemenu.getChildViewHolder(v);
            Drawable _drawable=getResources().getDrawable(BodyColor.left_menu_body);
            viewHolder.getDataBinding().fmPress.setBackground(_drawable);
        }
        binding.includeMenu.textView3.setTextColor(getResources().getColor(BodyColor.textcolor));
        binding.includeMenu.textView11.setTextColor(getResources().getColor(BodyColor.textcolor));
        binding.includeMenu.tvSpacesize.setTextColor(getResources().getColor(BodyColor.textcolor));
        Glide.with( this ).load( BodyColor.backgroundimage).asBitmap().into( binding.fmmain.qiniuMain );
        Glide.with( this ).load(BodyColor.backgroundhead).asBitmap().into( binding.includeHeard.imageView );
        //提示重绘
        _fmMain_vm._leftMenu_adapter.notifyDataSetChanged();
    }
    @Override
    public void onClick(View IView) {
        int i=IView.getId();
        if (i == R.id.tv_addspace) {
            final EditText input=new EditText(this);
                new AlertDialog.Builder(this)
                    .setTitle("请输入空间名")
                    .setView(input)
                    .setPositiveButton("确定",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int which) {
                                    String value = input.getText().toString ();
                                    FileManager2.addSpaceName(getApplicationContext(),value);
                                }
                             }).create().show();


        }
    }
    //数据初始化绑定
    private void onBindData(){
        ProgressDialog waitingDialog= new ProgressDialog(this);
            waitingDialog.setTitle("数据初始化");
            waitingDialog.setMessage("初始化中...");
            waitingDialog.setIndeterminate(true);
            waitingDialog.setCancelable(false);
            waitingDialog.show();

        _fmMain_vm=new FMMain_VM(getApplicationContext(),binding,waitingDialog);
        _fmMain_vm.init(new String[]{"沙杰", "陈煜"}, new ICallBack<Boolean>() {
            @Override
            public void success(Boolean items) {
                binding.fmmain.expandable.setOnItemClickListener(mIFileInfoOnclickListener);
            }
        }, new IFileInfoOnclickListener() {
            @Override
            public void deletListener(View IView, final int position, Item_FileInfo_module item) {
                if (TranModule.isaccount(((Item_FileInfo_module) binding.fmmain.searchBar.adapter.getItem(position)).getFilename())) {
                    MDialog.getInstance(FMMainActivity.this).delFile(item, new ICallBack<Bundle>() {
                        @Override
                        public void success(Bundle message) {
                            if (message.getInt("code")==200){
                                binding.fmmain.searchBar.adapter.removeAt(position);
                            }else {
                                Toast.makeText(FMMainActivity.this,message.getString("message"), Toast.LENGTH_SHORT).show();
                            }
                        }
                    });
                }else {
                    Toast.makeText(FMMainActivity.this, "没有权限删除！", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void downloadListener(View IView, int position) {
                MDialog.getInstance(FMMainActivity.this).downloadFile((Item_FileInfo_module) binding.fmmain.searchBar.adapter.getItem(position));
            }

            @Override
            public void showimgListener(View IView, int position) {
                String[] titles=TranModule.itemToArray((Item_FileInfo_module) binding.fmmain.searchBar.adapter.getItem(position));
                showImg(titles);
            }

            @Override
            public void onclickListener(View IView, final int position) {
                if (TranModule.isaccount(((Item_FileInfo_module) binding.fmmain.searchBar.adapter.getItem(position)).getFilename())) {
                    MDialog.getInstance(FMMainActivity.this).rename((Item_FileInfo_module) binding.fmmain.searchBar.adapter.getItem(position), new ICallBack<String>() {
                        @Override
                        public void success(String items) {
                            binding.fmmain.searchBar.adapter.changespace(position,items);
                        }
                    });
                }else {
                    Toast.makeText(FMMainActivity.this, "没有权限修改！", Toast.LENGTH_SHORT).show();
                }

            }
        });
        //
        binding.includeHeard.tvAccount.setText(Data.account);
    }

    //切换皮肤
    private void changeBodyColor(){
        initStatusBar();
        binding.includeMenu.switchButton.setOnCheckedChangeListener(new SwitchButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(SwitchButton view, boolean isChecked) {
                RippleAnimation.create(view).setDuration(300).start();
                if (isChecked){
                    BodyColor.setNightBody();
                    initBody();
                   // binding.includeMenu.constlayout.setBackgroundColor(Color.BLACK);
                }else{
                    BodyColor.setDayBody();
                    initBody();
                  //  binding.includeMenu.constlayout.setBackgroundColor(Color.WHITE);
                }
            }
        });

    }
    //皮肤动画
    private void initStatusBar() {
        Window window = getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS,
                WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS | WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
            window.setNavigationBarColor(Color.TRANSPARENT);
        }
    }
    @Override
    public void onBackPressed() {
        if (binding.fmmain.searchBar.isSearchOpen()) {
            binding.fmmain.searchBar.closeSearch();
            return;
        }
        if (binding.drawerLayout.isDrawerOpen(GravityCompat.START)) {
            binding.drawerLayout.closeDrawer(GravityCompat.START);
            return;
        }
            super.onBackPressed();

    }
    @Override
    protected void onDestroy() {
        Data.mInstance=null;
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
       if (requestCode == MaterialSearchView.REQUEST_VOICE && resultCode == RESULT_OK) {
            ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
            if (matches != null && matches.size() > 0) {
                String searchWrd = matches.get(0);
                if (!TextUtils.isEmpty(searchWrd)) {
                    binding.fmmain.searchBar.setQuery(searchWrd, false);
                }
            }
            return;
        }else if (requestCode==FM_File_Info_fragment.requestCode && resultCode == RESULT_OK){
            Uri uri=data.getData();
            String path= FilePath.getPath(getApplicationContext(),uri);
            ((FM_File_Info_fragment)getSupportFragmentManager().findFragmentByTag(fragmentflag)).upLoadFile(path);
        }else if (requestCode==REQUESTCODE && resultCode == RESULT_OK){
           Uri uri=data.getData();
           final String path= FilePath.getPath(getApplicationContext(),uri);
           new AlertDialog.Builder(FMMainActivity.this) // build AlertDialog
                .setTitle("选择空间") // title
                .setItems(Data.getInstance().SPACES.toArray(new String[Data.getInstance().SPACES.size()]), new  DialogInterface.OnClickListener() { //content
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        MDialog.getInstance(FMMainActivity.this).upLoadFile(path,Data.getInstance().SPACES.get(which));

                    }
                }) .show();


       }
        super.onActivityResult(requestCode, resultCode, data);
    }

    private IFileInfoOnclickListener mIFileInfoOnclickListener=new IFileInfoOnclickListener() {
        @Override
        public void deletListener(View IView, final int position, Item_FileInfo_module item) {
            //Toast.makeText(FMMainActivity.this, ""+item.filename, Toast.LENGTH_SHORT).show();
            if (TranModule.isaccount(binding.fmmain.expandable.getItem(position).getFilename())) {
                MDialog.getInstance(FMMainActivity.this).delFile(item, new ICallBack<Bundle>() {
                    @Override
                    public void success(Bundle message) {
                        if (message.getInt("code")==200){
                            binding.fmmain.expandable.removeViewAt(position);
                            binding.fmmain.expandable.delItem(position);

                            binding.fmmain.expandable.setOnItemClickListener(mIFileInfoOnclickListener);
                        }else {
                            Toast.makeText(FMMainActivity.this,message.getString("message"), Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }else {
                Toast.makeText(FMMainActivity.this, "没有权限删除！", Toast.LENGTH_SHORT).show();
            }
        }

        @Override
        public void downloadListener(View IView, int position) {
            MDialog.getInstance(FMMainActivity.this).downloadFile(binding.fmmain.expandable.getItem(position));
        }
        @Override
        public void showimgListener(View IView, int position) {
            String[] titles=TranModule.itemToArray(binding.fmmain.expandable.getItem(position));
            showImg(titles);
        }

        @Override
        public void onclickListener(View IView, final int position) {
            if (TranModule.isaccount(binding.fmmain.expandable.getItem(position).getFilename())) {
                MDialog.getInstance(FMMainActivity.this).rename(binding.fmmain.expandable.getItem(position), new ICallBack<String>() {
                    @Override
                    public void success(String items) {
                        binding.fmmain.expandable.changespace(position, items);

                    }
                });
            }else {
                Toast.makeText(FMMainActivity.this, "没有权限修改！", Toast.LENGTH_SHORT).show();
            }
        }
    };
    //跳转显示图片
    private void showImg(String[] titles){
        if (titles[2].matches(".+\\.(jpg|jpeg|png|gif|JPG|JPEG|PNG|GIF)")) {
            getSupportFragmentManager().beginTransaction().addToBackStack(null)
                    .setCustomAnimations(R.anim.in_from_left, R.anim.in_from_right, R.anim.out_from_left, R.anim.out_from_right)
                    .add(R.id.drawer_layout, FM_ShowPicture_fragment.getInstance(titles))
                    .commit();
        }
    }
    //动态请求权限
    private static final int REQUEST_EXTERNAL_STORAGE = 848;
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE
    };
    //权限回掉
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        switch (requestCode) {
            case REQUEST_EXTERNAL_STORAGE:
                if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                } else {
                    Toast.makeText(this, "未允许相关权限", Toast.LENGTH_SHORT).show();
                }
                break;
            default:
        }
    }
}
